package com.zy.fee.roadpark.activity.nb;

import android.content.Context;
import android.content.Intent;
import android.inputmethodservice.Keyboard;
import android.os.Bundle;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import com.flyco.roundview.RoundTextView;
import com.zy.fee.roadpark.R;
import com.zy.fee.roadpark.config.Constants;
import com.zy.fee.roadpark.dao.NbNodeRecordLogic;
import com.zy.fee.roadpark.model.M_NodeRecord;
import com.zy.fee.roadpark.model.apimodel.APIM_NodeRecordInfo;
import com.zy.fee.roadpark.util.Printer;
import com.zy.fee.roadpark.view.CommonDialog;
import com.zygk.library.base.BaseActivity;
import com.zygk.library.util.Convert;
import com.zygk.library.util.HttpRequest;
import com.zygk.library.util.LibraryHelper;
import com.zygk.library.util.PreferencesHelper;
import com.zygk.library.util.StringUtils;
import com.zygk.library.util.ToastUtil;
import com.zygk.library.view.AutoResizeTextView;
import com.zygk.library.view.XKeyboardView;
import com.zygk.library.view.gridpasswordview.GridPasswordView;

/**
 * 收款
 * Created by qhj on 2018/9/17 0017.
 */

public class NbReceivablesActivity extends BaseActivity {
  public static final String INTENT_CODE = "INTENT_CODE";
  public static final String INTENT_PLATE_NUMBER = "INTENT_PLATE_NUMBER";

  @BindView(R.id.lh_tv_title) TextView lhTvTitle;
  @BindView(R.id.et_code) EditText etCode;
  @BindView(R.id.gpvPlateNumber) GridPasswordView gpvPlateNumber;
  @BindView(R.id.iv_photo) ImageView ivPhoto;
  @BindView(R.id.tv_time) AutoResizeTextView tvTime;
  @BindView(R.id.tv_money) TextView tvMoney;
  @BindView(R.id.view_keyboard) XKeyboardView viewKeyboard;
  @BindView(R.id.rtv_complete) RoundTextView rtvComplete;

  private M_NodeRecord nodeRecord;

  @Override public void setContentView() {
    setContentView(R.layout.activity_nb_receivables);
  }

  @Override public void init() {
    initData();
    initView();
    initListener();
  }

  private void initData() {
    String code = getIntent().getStringExtra(INTENT_CODE);
    String plateNumber = getIntent().getStringExtra(INTENT_PLATE_NUMBER);
    if (!StringUtils.isBlank(code) && !StringUtils.isBlank(plateNumber)) {
      etCode.setText(code);
      gpvPlateNumber.setPassword(plateNumber);
      rtvComplete.setVisibility(View.GONE);
      nbnode_searchrecord_unpay();
    }
  }

  private void initView() {
    lhTvTitle.setText("收款");
  }

  private void initListener() {
    viewKeyboard.setIOnKeyboardListener(new XKeyboardView.IOnKeyboardListener() {
      @Override public void onInsertKeyEvent(String text) {
        gpvPlateNumber.appendPassword(text);
      }

      @Override public void onDeleteKeyEvent() {
        gpvPlateNumber.deletePassword();
      }
    });

    gpvPlateNumber.togglePasswordVisibility();

    gpvPlateNumber.setOnPasswordChangedListener(new GridPasswordView.OnPasswordChangedListener() {
      @Override public boolean beforeInput(int position) {
        if (position == 0) {
          viewKeyboard.setKeyboard(new Keyboard(mContext, R.xml.provice));
          viewKeyboard.setVisibility(View.VISIBLE);
          return true;
        } else if (position >= 1 && position < 2) {
          viewKeyboard.setKeyboard(new Keyboard(mContext, R.xml.english));
          viewKeyboard.setVisibility(View.VISIBLE);
          return true;
        } else if ((position >= 2 && position < 6) || position == 7) {
          viewKeyboard.setKeyboard(new Keyboard(mContext, R.xml.qwerty_without_chinese));
          viewKeyboard.setVisibility(View.VISIBLE);
          return true;
        } else if (position >= 6 && position < 7) {
          viewKeyboard.setKeyboard(new Keyboard(mContext, R.xml.qwerty));
          viewKeyboard.setVisibility(View.VISIBLE);
          return true;
        }
        viewKeyboard.setVisibility(View.GONE);
        return false;
      }

      @Override public void onTextChanged(String psw) {
      }

      @Override public void onInputFinish(String psw) {
      }
    });

    etCode.setOnFocusChangeListener(new View.OnFocusChangeListener() {
      @Override public void onFocusChange(View view, boolean hasFocus) {
        if (hasFocus) {
          viewKeyboard.setVisibility(View.GONE);
        } else {
          InputMethodManager imm =
              (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
          imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);
        }
      }
    });
  }

  private void printTicket() {
    if (null == nodeRecord) {
      ToastUtil.showMessage(mContext, "没有缴费停车单");
      return;
    }
    try {
      Printer.printT(nodeRecord.getCarNumber(), nodeRecord.getStartTime(), Constants.PAY_NB_URL + nodeRecord.getNodeRecordID(), false, preferencesHelper.getSettingString(PreferencesHelper.User.Key.LOT_ID));
      //打印完
      nbnode_record_pay_admin();
    } catch (
        Exception e) {
      e.printStackTrace();
    }
  }

  @Override protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ButterKnife.bind(this);
  }

  @OnClick({ R.id.ll_back, R.id.iv_code, R.id.rtv_confirm, R.id.rtv_receive, R.id.rtv_complete, R.id.rtv_pay })
  public void onViewClicked(View view) {
    switch (view.getId()) {
      case R.id.ll_back:
        finish();
        break;
      case R.id.iv_code:
      case R.id.rtv_pay:
        if (null == nodeRecord) {
          ToastUtil.showMessage(mContext, "未找到停车单");
          return;
        }
        if (!StringUtils.isBlank(nodeRecord.getNodeRecordID())) {
          CommonDialog.showQrCodeDialog(mContext,
              Constants.PAY_NB_URL + nodeRecord.getNodeRecordID());
        }
        break;
      case R.id.rtv_confirm:
        viewKeyboard.setVisibility(View.GONE);
        nbnode_searchrecord_unpay();
        break;
      case R.id.rtv_receive:
        if (nodeRecord == null) {
          ToastUtil.showMessage(mContext, "请先输入车位号和车牌号并点击确认按钮");
          return;
        }
        viewKeyboard.setVisibility(View.GONE);
        CommonDialog.showYesOrNoDialog(mContext, "确定完成现金收款吗?", "取消", "确定", () -> {
          printTicket();
        }, () -> {
        });
        break;
      case R.id.rtv_complete:
        if (nodeRecord == null) {
          ToastUtil.showMessage(mContext, "请先输入车位号和车牌号并点击确认按钮");
          return;
        }
        viewKeyboard.setVisibility(View.GONE);
        nbnode_record_pay_admin();
        break;
    }
  }

  private void nbnode_searchrecord_unpay() {
    String plateNo = gpvPlateNumber.getPassWord().replace(" ", "");
    String code = etCode.getText().toString();
    if (StringUtils.isBlank(code)) {
      ToastUtil.showMessage(mContext, "请输入车位号");
      return;
    }
    if (StringUtils.isBlank(plateNo)) {
      ToastUtil.showMessage(mContext, "请输入车牌号");
      return;
    }
    if (plateNo.length() < 7) {
      ToastUtil.showMessage(mContext, "车牌号不小于7位");
      return;
    }
    NbNodeRecordLogic.nbnode_searchrecord_unpay(mContext, LibraryHelper.userManager().getUserID(),
        code, plateNo, new HttpRequest.HttpCallback() {
          @Override public void onStart() {
            showNoCancelPd();
          }

          @Override public void onSucceed(Object obj) {
            APIM_NodeRecordInfo result = (APIM_NodeRecordInfo) obj;
            if (result.getIsFind() == 1) {
              nodeRecord = result.getNodeRecordInfo();
              imageManager.loadUrlImage(nodeRecord.getPic(), ivPhoto);
              tvMoney.setText(Convert.getMoneyString(nodeRecord.getMoney()));
              tvTime.setText(getTime(nodeRecord.getMin()));
            } else {
              ToastUtil.showMessage(mContext, "未找到停车单");
            }
          }

          @Override public void onFailed() {
            ToastUtil.showNetErrorMessage(mContext);
          }

          @Override public void onFinish() {
            dismissPd();
          }
        });
  }

  private void nbnode_record_pay_admin() {
    NbNodeRecordLogic.nbnode_record_pay_admin(mContext, LibraryHelper.userManager().getUserID(),
        nodeRecord.getNodeRecordID(), new HttpRequest.HttpCallback() {
          @Override public void onStart() {
            showNoCancelPd();
          }

          @Override public void onSucceed(Object obj) {
            sendBroadcast(new Intent(Constants.BROADCAST_REFRESH_NODE_LIST));
            ToastUtil.showMessage(mContext, "已完成收款");
            finish();
          }

          @Override public void onFailed() {
            ToastUtil.showNetErrorMessage(mContext);
          }

          @Override public void onFinish() {
            dismissPd();
          }
        });
  }

  private String getTime(long time) {
    int m = (int) time % 60;
    int h = (int) time / 60;
    return String.format("%02d:%02d:00", h, m);
  }

  @Override protected void onDestroy() {
    super.onDestroy();
  }
}
